//
//  WelcomeView.swift
//  FWSinaWeibo
//
//  Created by 范伟 on 16/2/26.
//  Copyright © 2016年 FanWei. All rights reserved.
//

import UIKit
/// 自定义欢迎视图
class WelcomeView: UIView {
    /// 声明两个控件
    private lazy var avatarView = UIImageView(fw_imageName: "avatar_default_big")
    private lazy var welcomeLabel = UILabel(fw_text: "欢迎归来，" + (UserAccount.sharedInstance.screen_name!) ?? "", fontSize: 18)
    
    override init(frame: CGRect) {
        super.init(frame: UIScreen.mainScreen().bounds)
//        backgroundColor = UIColor.orangeColor()
        setupUI()
    }
    func setupUI() {
        //指定图片设置为当前view的背景色
        backgroundColor = UIColor(patternImage: UIImage(named: "ad_background")!)
        addSubview(avatarView)
        addSubview(welcomeLabel)
        
        let iconWH: CGFloat = 50
        avatarView.layer.cornerRadius = iconWH
        avatarView.layer.masksToBounds = true
        
        //SnapKit自动布局
        
        avatarView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self)
            make.centerY.equalTo(self).offset(100)
            make.size.equalTo(CGSize(width: iconWH * 2, height: iconWH * 2))
        }
        
        welcomeLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(avatarView)
            make.centerY.equalTo(avatarView.snp_bottom).offset(20)
        }
        //立即应用约束
        layoutIfNeeded()
        avatarView.fw_setImageWithURL(UserAccount.sharedInstance.avatar_large, placeholderName: "avatar_default_big")
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit {
        print("\(classForCoder) \(__FUNCTION__)")
    }
    
}
// MARK: - 生命周期函数
extension WelcomeView {
    
    override func didMoveToSuperview() {
        super.didMoveToSuperview()
        NSLog("\(classForCoder) \(__FUNCTION__)")
    }
    
    override func didMoveToWindow() {
        super.didMoveToWindow()
        NSLog("\(classForCoder) \(__FUNCTION__)")
        
        //更新约束
        avatarView.snp_updateConstraints { (make) -> Void in
            make.centerY.equalTo(self).offset(-100)
        }
        
        //应用弹力动画
        UIView.animateWithDuration(1.5,
            delay: 0,
            usingSpringWithDamping: 0.8,
            initialSpringVelocity: 10,
            options: [],
            animations: { () -> Void in
                self.layoutIfNeeded()
            }) { (_) -> Void in
                let when = dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_MSEC) * 2))
                dispatch_after(when, dispatch_get_main_queue()){
                    self.removeFromSuperview()
                }
        }
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        NSLog("\(classForCoder) \(__FUNCTION__)")
    }
}
